module.exports = app => {
  const util = require('../../util/util.js')
  const route = require("express").Router({
    mergeParams: true
  });
  const mongoose = require('mongoose')
  const multer = require("multer")
  const upload = multer({
    dest: __dirname + '/../../uploads/'
  })
  app.post("/api/upload", upload.single("file"), (req, res) => {
    const file = req.file
    file.url = `http://wx.pipipi.net/uploads/${file.filename}`
    res.send(util.handleSuc({ data: file }))
  })
  app.use("/api/server/:resource", (req, res, next) => {
    let modelName = require("inflection").classify(req.params.resource);
    const Model = require(`../../models/${modelName}`);
    req.model = Model;
    next();
  }, route);

  //通用增加接口
  route.post('/', async (req, res) => {
    const qModel = await req.model.findOne(req.body)
    if (qModel) {
      res.send(util.handleFail('已存在，请更换参数尝试', 403))
    } else {
      const model = await req.model.create(req.body)
      res.send(util.handleSuc(model))
    }
  })

  // 通用更新
  route.put('/:id', async (req, res) => {
    let options = {}
    if (req.model.modelName === 'OrderSku') {
      options.populate = 'products.product'
    }
    const model = await req.model.findByIdAndUpdate(req.params.id, req.body, { new: true }).setOptions(options)
    res.send(util.handleSuc(model))
  })

  // 通用删除
  route.delete('/:id', async (req, res) => {
    // await req.model.find(req.query)
    const data = await req.model.findByIdAndDelete(req.params.id)
    res.send(util.handleSuc(data))
  })

  //通用 GET接口
  route.get('/', async (req, res) => {
    let query = {}
    let options = {}
    if (req.model.modelName === 'ServiceProduct') {
      options.populate = 'category'
    }
    if (req.model.modelName === 'OrderSku') {
      options.populate = 'products.product'
    }
    if (req.model.modelName === 'ShoppingCart') {
      options.populate = 'product'
    }
    let page = req.query.page ? req.query.page : 1
    query = {
      ...req.query
    }
    delete query.page

    const keys = Object.keys(query)
    keys.forEach(key => {
      if (!query[key])
        delete query[key]
    })
    const items = await req.model.find(query).setOptions(options).skip(6 * (--page)).limit(6)
    const total = await req.model.find(query).count()

    res.send(util.handleSuc({ list: [...items], total }))
  })

  route.get('/:id', async (req, res) => {
    if (mongoose.Types.ObjectId.isValid(req.params.id)) {
      let options = {}
      if (req.model.modelName === 'OrderSku') {
        options.populate = ['products.product', 'address']
      }
      const model = await req.model.findById(req.params.id).setOptions(options)
      if (model) {
        res.send(util.handleSuc(model))
      } else {
        res.send(util.handleFail(`${req.model}不存在`))
      }
    } else {
      res.send(util.handleFail('非法参数'))
    }
  })

}
